<?php
session_start();
require_once 'dbconnector.php';
require_once 'emailHelper.php';
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
if(isset($_GET['task']))
{
    $task = $_GET['task'];
    if($task=="login")
    {
        $username=mysql_real_escape_string(htmlentities($_POST['username']));
        $password=mysql_real_escape_string(htmlentities($_POST['password']));
        $password=md5($password);        
        $query = "SELECT * FROM user WHERE email='$username' AND password='$password' AND isActive=1";
        $result = mysql_query($query);
        if(mysql_num_rows($result)>0)
        {
            $_SESSION['auth']   = 1;
            $rows=mysql_fetch_array($result);
            $_SESSION['userid']=$rows['id'];
            $_SESSION['username']=$rows['nama'];
            header("Location: ../voting.php");
            exit(0);
        }
    }
    else if($task=="logout")
    {
        unset($_SESSION['auth']);
    }
    else if($task=="register")
    {
        $email = mysql_real_escape_string(htmlentities($_POST['email']));
        $password = md5(mysql_real_escape_string(htmlentities($_POST['password'])));
        $repass = md5(mysql_real_escape_string(htmlentities($_POST['repass'])));
        $name = mysql_real_escape_string(htmlentities($_POST['name']));
        $angkatan = mysql_real_escape_string(htmlentities($_POST['angkatan']));
        if($password==$repass)
        {
            $queryCekEmail = "SELECT * FROM user WHERE email='$email';";
            $resultCekEmail = mysql_query($queryCekEmail);
            if(mysql_num_rows($resultCekEmail)>0)
            {
                header("Location: ../index.php?err=2");
                exit(0);
            }
            else
            {
                $aktivasi = createActivationCode($email);
                $query = "INSERT INTO user (email,password,nama,angkatan,kode_konfirmasi) VALUES ('$email','$password','$name','$angkatan','$aktivasi')";
                $result = mysql_query($query);                
                //kirim email                
                $body = createBody($name, $aktivasi);
                sendEmail($email, $body);
                header("Location: ../index.php");
                exit(0);            
            }
            
        }
        else
        {
            header("Location: ../index.php?err=1");
        }
        
    }
   header("Location:../index.php?err=3");
   exit(0);
}
header("Location: ../index.php?err=4");
?>
